<template>
    <div class="app-container">
      <oqc-info ref="oqcInfo" :form="form" ></oqc-info>
      <el-divider content-position="center" >检验信息</el-divider>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验单编号" prop="oqcCode">
              <el-input v-model="form.oqcCode" readonly placeholder="请输入出货检验单编号" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="检验单名称" prop="oqcName">
              <el-input v-model="form.oqcName" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="本次检测数量" prop="quantityCheck">
              <el-input v-model="form.quantityCheck"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合格品数量" prop="quantityQualified">
              <el-input-number
                :min="0"
                :max="form.quantityCheck"
                v-model="form.quantityQualified"
                @change="jiSuanBuHege()"
                :disabled="oqclineList.length>0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="不合格数" prop="quantityUnqualified">
              <el-input-number
                :min="0"
                :max="form.quantityCheck"
                :disabled="oqclineList.length>0"
                @change="jiSuanHege()"
                v-model="form.quantityUnqualified"
              />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>

          <el-col :span="8">
            <el-form-item label="检测日期" prop="inspectDate">
              <el-date-picker clearable
                v-model="form.inspectDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择检测日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测结果" prop="checkResult">
              <el-select v-model="form.checkResult" placeholder="请选择检测结果">
                <el-option
                  v-for="dict in dict.type.mes_qc_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  v-if="dict.value !== 'EXEMPT'"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检测人员" prop="inspector">
              <el-input v-model="form.inspector" placeholder="请输入检测人员" readonly>
                <el-button slot="append" @click="handleSelectUser" icon="el-icon-search"></el-button>
              </el-input>
              <UserSelect ref="userSelect" @onSelected="onUserSelected" ></UserSelect>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="附件" prop="remark">
                <FileUpload
                  :limit="5"
                  :fileSize="100"
                  :fileType="fileType"
                  :value="fileList"
                  :optType="optType"
                  @onUploaded="handleUploaded"
                  @onRemoved="handleRemoved">
                </FileUpload>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form>
      <el-divider  content-position="center">检测项</el-divider>
      <el-card shadow="always" class="box-card">
        <Ipqcline ref="line" v-if="oqclineList.length>0" :ipqclineListFromParent="oqclineList" :realValueColumnsFromParent="realValueColumns"  :optType="optType"  @computeValue="computeValue1"></Ipqcline>
      </el-card>

      <el-form>
        <el-form-item style="margin-left: 40%;">
          <el-button type="primary" @click="submitForm" v-if="form.status === 'PREPARE'">保 存</el-button>
          <el-button type="success" @click="handleFinish" v-if="form.status === 'PREPARE' && form.oqcId !=null">完成</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>

    </div>
</template>
<script>
import { listOqc, getOqc, delOqc, addOqc, updateOqc, getQcOqcBySource } from "@/api/mes/qc/oqc";
import {genCode} from "@/api/system/autocode/rule";
import UserSelect from "@/components/userSelect/single.vue";
import { getUserProfile } from "@/api/system/user";
import oqcInfo from "@/views/mes/qc/pendinginspect/oqcInfo.vue";
import Ipqcline from "@/views/mes/qc/ipqc/line.vue";

export default {
  name: "Oqc",
  dicts: ['mes_order_status','mes_qc_result'],
  components: {
    Ipqcline,
    oqcInfo,
     UserSelect
  },
  data(){
    return {
      realValueColumns:[],
      resultArray:[],
      oqclineList:[],
      // 表单参数
      form: {},
      // 查看开关
      optType: undefined,
      // 上传文件类型
      fileType: ["pdf","doc", "xls","jpg","png"],
      // 上传文件列表
      fileList: [],
      queryParams: {
        sourceDocId: this.$route.params.sourceDocId,
        sourceDocCode: this.$route.params.sourceDocCode,
        sourceLineId: this.$route.params.sourceLineId,
      },
      // 表单校验
      rules: {
        oqcCode: [
          { required: true, message: "出货检验单编号不能为空", trigger: "blur" }
        ],
        quantityCheck: [
          { required: true, message: "本次检测数量不能为空", trigger: "blur" }
        ],
        inspectDate: [
          { required: true, message: "请选择检测日期", trigger: "blur" }
        ],
      },
      // 当前登录用户
      user: null,
    }
  },
  created() {
    getUserProfile().then(response => {
      this.user = response.data;
      this.init();
    });
  },
  methods: {
    computeValue1(ipqclineList){
      this.realValueColumns.forEach((it,index)=>{
        let result=true;
        ipqclineList.forEach(item => {
          //定性
          if(item.indexType == 'QUALITATIVE'){
            if(item.realValues[index]==0){
              result=false;
              return;
            }
          }else{
            if(item.realValues[index]<item.standerVal+item.thresholdMin||item.realValues[index]>item.standerVal+item.thresholdMax){
              result=false;
              return;
            }
          }
        });
        this.resultArray[index]=result;
      })
      let heGeShu=0;
      let buHeGeShu=0;
      this.resultArray.forEach(i=> {
        if(i!=null){
          if(i) {
            heGeShu++;
          }else{
            buHeGeShu++;
          }
        }
      })
      this.form.quantityQualified=heGeShu;
      this.form.quantityUnqualified = buHeGeShu;
    },
    jiSuanBuHege(){
      if(this.oqclineList==0){
        this.form.quantityUnqualified=this.form.quantityCheck-this.form.quantityQualified;
      }
    },
    jiSuanHege(){
      if(this.oqclineList==0){
        this.form.quantityQualified=this.form.quantityCheck-this.form.quantityUnqualified;
      }
    },
    init() {
      getQcOqcBySource(this.queryParams).then(response => {
        if (response.data) {
          this.form = response.data
          if(!this.form.oqcCode){
            genCode('OQC_CODE').then(response =>{
              this.form.oqcCode = response;
            });
          }
          if (this.form.inspector == null) {
            this.form.inspector = this.user.nickName;
          }
        }else {
          this.reset();
          genCode('OQC_CODE').then(response =>{
            this.form.oqcCode = response;
          });
        }
      })
    },
    // 取消按钮
    cancel() {
      const obj = { path: "/mes/qc/pendinginspect" };
      this.$tab.closeOpenPage(obj);
    },
    // 表单重置
    reset() {
      this.form = {
        oqcId: null,
        oqcCode: null,
        oqcName: null,
        templateId: null,
        sourceDocId: this.$route.params.sourceDocId,
        sourceDocType: this.$route.params.sourceDocType,
        sourceDocCode: this.$route.params.sourceDocCode,
        sourceLineId: this.$route.params.sourceLineId,
        clientId: this.$route.params.vendorClientId,
        clientCode: this.$route.params.vendorClientCode,
        clientName: this.$route.params.vendorClientName,
        batchCode: this.$route.params.batchCode,
        itemId: this.$route.params.itemId,
        itemCode: this.$route.params.itemCode,
        itemName: this.$route.params.itemName,
        specification: this.$route.params.specification,
        unitOfMeasure: this.$route.params.unitOfMeasure,
        quantityMinCheck: null,
        quantityMaxUnqualified: null,
        quantityOut: this.$route.params.quantityUncheck,
        quantityCheck: null,
        quantityUnqualified: null,
        quantityQuanlified: null,
        crRate: null,
        majRate: null,
        minRate: null,
        crQuantity: null,
        majQuantity: null,
        minQuantity: null,
        checkResult: null,
        outDate: this.$route.params.recordTime,
        inspectDate: new Date(),
        inspector: this.user.nickName,
        status: "PREPARE",
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        attr2: null,
      };

      this.resetForm("form");
      this.fileList = [];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.oqcId != null) {
            updateOqc(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addOqc(this.form).then(response => {
              this.form.oqcId = response.data
              this.$modal.msgSuccess("新增成功");
            });
          }
        }
      });
    },
    //点击完成
    handleFinish(){
      let that = this;
      if(this.form.checkResult == null){
        this.$modal.msgError("请选择检测结果！");
        return;
      }
      let out = parseInt(that.form.quantityOut);
      if (that.form.quantityCheck > out) {
        this.$modal.msgError("本次检测数量不能大于发货数量！");
        return;
      }
      if (that.form.quantityUnqualified > that.form.quantityCheck) {
        this.$modal.msgError("不合格数量不能大于本次检测数量！");
        return;
      }
      if (that.form.checkResult === 'REJECT') {
        if (that.form.quantityUnqualified <= 0) {
          this.$modal.msgError("不合格数量不能为0！")
        }
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否完成出货检验单编制？【完成后将不能更改】').then(function(){
            that.form.status = 'FINISHED';
            that.submitForm();
            that.cancel();
          });
        }
        });
    },

    // 结果统计回显
    handleReview() {
      getOqc(this.form.oqcId).then(response => {
        this.form = response.data;
        this.form.attr2 = response.data.attr2;
        response.data.attr2 === null ? this.fileList = [] : this.fileList = response.data.attr2.split(',');
      });
    },
    handleSelectUser(){
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj){
      if(obj != undefined && obj != null){
        this.form.inspector = obj.nickName;
      }
    },
    handleUploaded(data) {
      this.form.attr2 = data;
      this.optType = 'add';
    },
    handleRemoved(data) {
      this.form.attr2 = data;
      this.optType = 'add';
    },

  }

}
</script>
